package com.loong.web.gp4j.dao.attach;

import java.util.Date;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;

import com.google.gson.Gson;
import com.loong.web.gp4j.bean.schema.attach.AttachSchema;

/**
 * 代码缓存
 *
 * @author 张成轩
 */
@Repository
public class AttachCache {

	@Resource
	private RedisTemplate<String, String> template;
	@Resource
	private Gson gson;
	@Value("${cache.attach.expire}")
	private long expire;

	/** 存储键 */
	private static final String KEY = "attach:";

	/**
	 * 保存附件
	 * 
	 * @param sign 标识
	 * @param attach 附件对象
	 */
	public void put(String sign, AttachSchema attach) {

		String key = KEY + sign;
		template.opsForValue().set(key, gson.toJson(attach));
		template.expireAt(key, new Date(System.currentTimeMillis() + expire));
	}

	/**
	 * 获取附件
	 * 
	 * @param sign 标识
	 * @return 附件对象
	 */
	public AttachSchema get(String sign) {

		String value = template.opsForValue().get(KEY + sign);
		if (value == null)
			return null;
		return gson.fromJson(value, AttachSchema.class);
	}

	/**
	 * 删除附件
	 * 
	 * @param sign 标识
	 */
	public void remove(String sign) {

		template.delete(KEY + sign);
	}
}
